<template>
  <div class="register-page">
    <!-- Header -->
    <AppHeader />

    <!-- Main Content -->
    <div class="auth-container">
      <!-- Left Brand Section -->
      <div class="brand-section">
        <div class="brand-content">
          <div class="brand-logo">
            <NearLogo :size="48" variant="primary" />
          </div>
          <div class="brand-text">
            <h1 class="brand-title">{{ $t('auth.brandTitle') }}</h1>
            <h2 class="brand-subtitle">{{ $t('auth.brandSubtitle') }}</h2>
            <div class="brand-line"></div>
            <p class="brand-copyright">{{ $t('auth.brandCopyright') }}</p>
          </div>
        </div>

        <!-- 动态金融数据展示 -->
        <div class="financial-animation">
          <!-- 主要趋势图表 -->
          <div class="main-chart">
            <TrendChart :width="280" :height="100" :is-positive="true" />
          </div>

          <!-- 浮动价格卡片 -->
          <FloatingPriceCard
            v-for="(crypto, index) in cryptoData"
            :key="crypto.name"
            :crypto-data="crypto"
            :animation-delay="index * 0.5"
            :float-direction="index % 2 === 0 ? 'up' : 'down'"
            :style="getCardPosition(index)"
          />

          <!-- 统计数据展示 -->
          <div class="stats-display">
            <div class="stat-item">
              <div class="stat-label">총시가</div>
              <div class="stat-value">
                <AnimatedNumber :value="totalMarketCap" :decimals="0" suffix="B" />
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-label">24h거래량</div>
              <div class="stat-value">
                <AnimatedNumber :value="dailyVolume" :decimals="1" suffix="B" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Right Form Section -->
      <div class="form-section">
        <div class="form-container">
          <h2 class="form-title">{{ $t('auth.register.title') }}</h2>

          <el-form :model="registerForm" class="register-form" @submit.prevent="handleRegister">
            <!-- 1. 아이디 (身份证) -->
            <el-form-item :label="$t('auth.register.idNumber')">
              <el-input
                v-model="registerForm.idNumber"
                :placeholder="$t('auth.register.idPlaceholder')"
                size="large"
                class="form-input"
              />
            </el-form-item>

            <!-- 2. 이름 (姓名) -->
            <el-form-item :label="$t('auth.register.name')">
              <el-input
                v-model="registerForm.name"
                :placeholder="$t('auth.register.namePlaceholder')"
                size="large"
                class="form-input"
              />
            </el-form-item>

            <!-- 3. 출생년월일 앞6자리 -->
            <el-form-item :label="$t('auth.register.birthDateFirst6')">
              <el-input
                v-model="registerForm.birthDateFirst6"
                :placeholder="$t('auth.register.birthDatePlaceholder')"
                size="large"
                class="form-input"
                maxlength="6"
              />
            </el-form-item>

            <!-- 4. 비밀번호 -->
            <el-form-item :label="$t('auth.register.password')">
              <el-input
                v-model="registerForm.password"
                type="password"
                :placeholder="$t('auth.register.password')"
                size="large"
                class="form-input"
                show-password
              />
            </el-form-item>

            <!-- 5. 비밀번호 재입력 -->
            <el-form-item :label="$t('auth.register.confirmPassword')">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                :placeholder="$t('auth.register.confirmPassword')"
                size="large"
                class="form-input"
                show-password
              />
            </el-form-item>

            <!-- 6. 출금계좌 은행 -->
            <el-form-item :label="$t('auth.register.withdrawalBank')">
              <el-select
                v-model="registerForm.withdrawalBank"
                :placeholder="$t('auth.register.bankPlaceholder')"
                size="large"
                class="form-input"
                style="width: 100%"
              >
                <el-option label="KB국민은행" value="kb_kookmin" />
                <el-option label="신한은행" value="shinhan" />
                <el-option label="우리은행" value="woori" />
                <el-option label="하나은행" value="hana" />
                <el-option label="NH농협은행" value="nh_nonghyup" />
                <el-option label="IBK기업은행" value="ibk" />
                <el-option label="SC제일은행" value="sc_first" />
                <el-option label="씨티은행" value="citi" />
                <el-option label="KDB산업은행" value="kdb" />
                <el-option label="수출입은행" value="exim" />
                <el-option label="BNK부산은행" value="bnk_busan" />
                <el-option label="BNK경남은행" value="bnk_gyeongnam" />
                <el-option label="DGB대구은행" value="dgb_daegu" />
                <el-option label="광주은행" value="gwangju" />
                <el-option label="전북은행" value="jeonbuk" />
                <el-option label="제주은행" value="jeju" />
                <el-option label="카카오뱅크" value="kakao" />
                <el-option label="케이뱅크" value="k_bank" />
                <el-option label="토스뱅크" value="toss" />
                <el-option label="새마을금고" value="mg_saemaul" />
                <el-option label="수협은행" value="suhyup" />
                <el-option label="신협은행" value="shinhyup" />
                <el-option label="우체국" value="korea_post" />
              </el-select>
            </el-form-item>

            <!-- 7. 출금 계좌번호 -->
            <el-form-item :label="$t('auth.register.withdrawalAccount')">
              <el-input
                v-model="registerForm.withdrawalAccount"
                :placeholder="$t('auth.register.accountPlaceholder')"
                size="large"
                class="form-input"
              />
            </el-form-item>

            <!-- 8. 예금주 (持有) -->
            <el-form-item :label="$t('auth.register.accountHolder')">
              <el-input
                v-model="registerForm.accountHolder"
                :placeholder="$t('auth.register.holderPlaceholder')"
                size="large"
                class="form-input"
              />
            </el-form-item>

            <!-- 9. 통신사 -->
            <el-form-item :label="$t('auth.register.mobileCarrier')">
              <el-select
                v-model="registerForm.mobileCarrier"
                :placeholder="$t('auth.register.carrierPlaceholder')"
                size="large"
                class="form-input"
                style="width: 100%"
              >
                <el-option label="SKT" value="skt" />
                <el-option label="KT" value="kt" />
                <el-option label="LG U+" value="lguplus" />
                <el-option label="SKT알뜰폰" value="skt_mvno" />
                <el-option label="KT알뜰폰" value="kt_mvno" />
                <el-option label="LGU알뜰폰" value="lgu_mvno" />
                <el-option label="알뜰폰 (기타)" value="mvno_other" />
              </el-select>
            </el-form-item>

            <!-- 10. 휴대폰 번호 -->
            <el-form-item :label="$t('auth.register.mobileNumber')">
              <el-input
                v-model="registerForm.mobileNumber"
                :placeholder="$t('auth.register.mobilePlaceholder')"
                size="large"
                class="form-input"
              />
            </el-form-item>

            <!-- 11. 가입코드 -->
            <el-form-item :label="$t('auth.register.entryCode')">
              <el-input
                v-model="registerForm.entryCode"
                :placeholder="$t('auth.register.codePlaceholder')"
                size="large"
                class="form-input"
                :disabled="isEntryCodeFromUrl"
                clearable
              />
              <div v-if="isEntryCodeFromUrl" class="form-hint">
                파트너를 통해 등록하고 있습니다
              </div>
            </el-form-item>

            <!-- 12. 추천코드 (선택사항) -->
            <el-form-item :label="$t('auth.register.referralCode')">
              <el-input
                v-model="registerForm.referralCode"
                :placeholder="$t('auth.register.referralCodePlaceholder')"
                size="large"
                class="form-input"
                :disabled="isReferralCodeFromUrl"
                clearable
              />
              <div class="form-hint">
                {{ isReferralCodeFromUrl ? '추천인을 통해 등록하고 있습니다' : $t('auth.register.referralCodeHint') }}
              </div>
            </el-form-item>

            <el-form-item>
              <el-checkbox v-model="registerForm.agreeTerms" class="terms-checkbox">
                {{ $t('auth.register.agreeTerms') }}
              </el-checkbox>
            </el-form-item>

            <div class="form-actions">
              <el-button
                type="primary"
                size="large"
                class="register-btn"
                @click="handleRegister"
                :disabled="!registerForm.agreeTerms"
              >
                {{ $t('auth.register.registerBtn') }}
              </el-button>
            </div>

            <div class="login-link">
              <span>{{ $t('auth.register.hasAccount') }}</span>
              <router-link to="/login" class="link">
                {{ $t('auth.register.loginLink') }}
              </router-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { api } from '@/utils/request'
import AppHeader from '@/components/Header/AppHeader.vue'
import NearLogo from '@/components/Common/NearLogo.vue'
import FloatingPriceCard from '@/components/Common/FloatingPriceCard.vue'
import AnimatedNumber from '@/components/Common/AnimatedNumber.vue'
import TrendChart from '@/components/Common/TrendChart.vue'

const router = useRouter()
const route = useRoute()

// 动态金融数据
const totalMarketCap = ref(0)
const dailyVolume = ref(0)

const cryptoData = ref([
  {
    name: 'NEAR',
    icon: 'cryptocurrency:near',
    price: 4.52,
    change: 5.23,
    decimals: 2
  },
  {
    name: 'BTC',
    icon: 'cryptocurrency:btc',
    price: 43250.00,
    change: -2.15,
    decimals: 0
  },
  {
    name: 'ETH',
    icon: 'cryptocurrency:eth',
    price: 2680.45,
    change: 3.84,
    decimals: 0
  },
  {
    name: 'BNB',
    icon: 'cryptocurrency:bnb',
    price: 315.20,
    change: 1.92,
    decimals: 2
  }
])

// 获取卡片位置
const getCardPosition = (index: number) => {
  const positions = [
    { top: '5%', right: '20%' },
    { top: '25%', left: '5%' },
    { top: '45%', left: '25%' },
    { top: '15%', right: '5%' }
  ]
  return positions[index] || { top: '40%', left: '50%' }
}

const registerForm = ref({
  idNumber: '',           // 아이디 (身份证)
  name: '',               // 이름 (姓名)
  birthDateFirst6: '',    // 출생년월일 앞6자리
  password: '',           // 비밀번호
  confirmPassword: '',    // 비밀번호 재입력
  withdrawalBank: '',     // 출금계좌 은행
  withdrawalAccount: '',  // 출금 계좌번호
  accountHolder: '',      // 예금주 (持有)
  mobileCarrier: '',      // 통신사
  mobileNumber: '',       // 휴대폰 번호
  entryCode: '',          // 가입코드
  referralCode: '',       // 추천코드 (선택사항)
  agreeTerms: false       // 이용약관 동의
})

// 标记推荐码是否来自URL（如果是，则禁用编辑）
const isReferralCodeFromUrl = ref(false)

// 标记入会码是否来自URL（如果是，则禁用编辑）
const isEntryCodeFromUrl = ref(false)

// 验证函数
const validateBirthDate = (birthDate: string): boolean => {
  const regex = /^\d{6}$/
  return regex.test(birthDate)
}

const validateMobileNumber = (mobile: string): boolean => {
  const regex = /^010-?\d{4}-?\d{4}$/
  return regex.test(mobile)
}

const validateForm = (): boolean => {
  const form = registerForm.value

  // 检查必填字段
  if (!form.idNumber) {
    ElMessage.error('6자이상으로 만들어주세요.')
    return false
  }

  if (!form.name) {
    ElMessage.error('이름을 입력하세요.')
    return false
  }

  if (!form.birthDateFirst6) {
    ElMessage.error('출생년월일 앞6자리를 입력하세요.')
    return false
  }

  if (!validateBirthDate(form.birthDateFirst6)) {
    ElMessage.error('출생년월일은 6자리 숫자여야 합니다. (예: 901225)')
    return false
  }

  if (!form.password) {
    ElMessage.error('비밀번호를 입력하세요.')
    return false
  }

  if (!form.confirmPassword) {
    ElMessage.error('비밀번호를 다시 입력하세요.')
    return false
  }

  if (form.password !== form.confirmPassword) {
    ElMessage.error('비밀번호가 일치하지 않습니다.')
    return false
  }

  if (!form.withdrawalBank) {
    ElMessage.error('출금계좌 은행을 선택하세요.')
    return false
  }

  if (!form.withdrawalAccount) {
    ElMessage.error('출금 계좌번호를 입력하세요.')
    return false
  }

  if (!form.accountHolder) {
    ElMessage.error('예금주를 입력하세요.')
    return false
  }

  if (!form.mobileCarrier) {
    ElMessage.error('통신사를 선택하세요.')
    return false
  }

  if (!form.mobileNumber) {
    ElMessage.error('휴대폰 번호를 입력하세요.')
    return false
  }

  if (!validateMobileNumber(form.mobileNumber)) {
    ElMessage.error('올바른 휴대폰 번호 형식이 아닙니다. (예: 010-1234-5678)')
    return false
  }

  // entryCode 为可选字段,不进行必填验证

  if (!form.agreeTerms) {
    ElMessage.warning('이용약관에 동의해주세요.')
    return false
  }

  return true
}

const handleRegister = async () => {
  if (!validateForm()) {
    return
  }

  try {
    // 调用注册API
    const response = await api.post('/api/auth/register', {
      idNumber: registerForm.value.idNumber,
      name: registerForm.value.name,
      birthDateFirst6: registerForm.value.birthDateFirst6,
      password: registerForm.value.password,
      withdrawalBank: registerForm.value.withdrawalBank,
      withdrawalAccount: registerForm.value.withdrawalAccount,
      accountHolder: registerForm.value.accountHolder,
      mobileCarrier: registerForm.value.mobileCarrier,
      mobileNumber: registerForm.value.mobileNumber,
      entryCode: registerForm.value.entryCode,
      referralCode: registerForm.value.referralCode.trim() || undefined // 推荐码（可选）
    })

    // 注册成功
    const { user, token } = response.data

    // 存储token到localStorage
    localStorage.setItem('user_token', token)

    // 显示成功消息
    ElMessage.success(`회원가입이 완료되었습니다! 환영합니다, ${user.name}님!`)

    // 自动登录并跳转到dashboard
    router.push('/app/dashboard')

  } catch (error: any) {
    console.error('회원가입 실패:', error)
    // 错误消息会在request拦截器中处理
  }
}

// 初始化动画数据
onMounted(() => {
  // 检查URL中是否有推荐码参数
  const referralCodeParam = route.query.referralCode as string
  if (referralCodeParam) {
    registerForm.value.referralCode = referralCodeParam
    isReferralCodeFromUrl.value = true
    console.log('URL에서 추천 코드를 가져왔습니다:', referralCodeParam)
  }

  // 检查URL中是否有合作伙伴邀请码参数
  const entryCodeParam = route.query.entryCode as string
  if (entryCodeParam) {
    registerForm.value.entryCode = entryCodeParam
    isEntryCodeFromUrl.value = true
    console.log('URL에서 파트너 초대 코드를 가져왔습니다:', entryCodeParam)
  }

  // 延迟启动数据动画，营造逐步加载的效果
  setTimeout(() => {
    totalMarketCap.value = 2340
    dailyVolume.value = 58.7
  }, 1000)

  // 定期更新价格数据以模拟实时效果
  const priceUpdateInterval = setInterval(() => {
    cryptoData.value.forEach(crypto => {
      const changePercent = (Math.random() - 0.5) * 0.1 // ±5%的随机变化
      crypto.price = Math.max(0.01, crypto.price * (1 + changePercent))
      crypto.change = (Math.random() - 0.5) * 10 // ±5%的涨跌幅
    })
  }, 5000)

  // 清理定时器
  const cleanup = () => clearInterval(priceUpdateInterval)

  // 在组件卸载时清理
  if (typeof window !== 'undefined') {
    window.addEventListener('beforeunload', cleanup)
  }
})
</script>

<style scoped lang="scss">
.register-page {
  min-height: 100vh;
  background: white;
  display: flex;
  flex-direction: column;
}


.auth-container {
  flex: 1;
  display: flex;
  min-height: calc(100vh - 64px);
}

.brand-section {
  flex: 1;
  background: white;
  display: flex;
  align-items: flex-end;
  justify-content: flex-start;
  padding: 40px;
  position: relative;
  overflow: hidden;

  .brand-content {
    text-align: left;
    max-width: 500px;
    color: #1a202c;

    .brand-logo {
      position: absolute;
      top: -60px;
      left: -20px;
    }

    .brand-text {
      .brand-title {
        font-size: 36px;
        font-weight: 600;
        color: #1a202c;
        margin-bottom: 12px;
        line-height: 1.2;
      }

      .brand-subtitle {
        font-size: 20px;
        font-weight: 400;
        color: #64748b;
        margin-bottom: 24px;
        line-height: 1.4;
      }

      .brand-line {
        width: 60px;
        height: 4px;
        background: #7c3aed;
        margin-bottom: 24px;
      }

      .brand-copyright {
        font-size: 15px;
        color: #94a3b8;
        line-height: 1.4;
      }
    }
  }

  // 动态金融数据展示样式
  .financial-animation {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
    z-index: 1;

    .main-chart {
      position: absolute;
      top: 20%;
      right: 10%;
      opacity: 0.7;
      animation: fadeInChart 2s ease-out 0.5s both;
    }

    .stats-display {
      position: absolute;
      bottom: 30%;
      right: 15%;
      display: flex;
      gap: 20px;
      animation: slideInStats 1.5s ease-out 1.5s both;

      .stat-item {
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(124, 58, 237, 0.1);
        border-radius: 12px;
        padding: 16px;
        text-align: center;
        box-shadow: 0 4px 20px rgba(124, 58, 237, 0.1);
        transition: transform 0.3s ease;

        &:hover {
          transform: translateY(-2px);
        }

        .stat-label {
          font-size: 12px;
          color: #64748b;
          margin-bottom: 8px;
          font-weight: 500;
        }

        .stat-value {
          font-size: 18px;
          font-weight: 700;
          color: #1a202c;
        }
      }
    }
  }

  .brand-content {
    z-index: 10;
    position: relative;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(5px);
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  }
}

.form-section {
  flex: 1;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;

  .form-container {
    width: 100%;
    max-width: 400px;
    background: white;
    padding: 40px;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border: 1px solid #e2e8f0;
    max-height: 80vh;
    overflow-y: auto;

    .form-title {
      font-size: 32px;
      font-weight: 600;
      color: #1a202c;
      text-align: center;
      margin-bottom: 32px;
      white-space: nowrap;
    }

    .register-form {
      :deep(.el-form-item) {
        margin-bottom: 20px;
        display: flex;
        flex-direction: row;
        align-items: center;

        .el-form-item__label {
          color: #374151;
          font-weight: 500;
          font-size: 14px;
          line-height: 1.5;
          margin-bottom: 0;
          text-align: left;
          width: 120px !important;
          min-width: 120px;
          padding: 0 12px 0 0 !important;
          position: relative;
          float: none !important;
          flex-shrink: 0;
        }

        .el-form-item__content {
          margin-left: 0 !important;
          flex: 1;
          width: auto;
        }
      }

      .form-input {
        margin-bottom: 16px;

        :deep(.el-input__wrapper) {
          border-radius: 8px;
          padding: 12px 16px;
          border: 1px solid #e2e8f0;

          &:hover {
            border-color: #7c3aed;
          }

          &.is-focus {
            border-color: #7c3aed;
            box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
          }
        }

        :deep(.el-select__wrapper) {
          border-radius: 8px;
          padding: 12px 16px;
          border: 1px solid #e2e8f0;

          &:hover {
            border-color: #7c3aed;
          }

          &.is-focus {
            border-color: #7c3aed;
            box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
          }
        }
      }

      .terms-checkbox {
        margin-bottom: 24px;

        :deep(.el-checkbox__label) {
          font-size: 14px;
          color: #64748b;
        }

        :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
          background-color: #7c3aed;
          border-color: #7c3aed;
        }
      }

      .form-hint {
        font-size: 12px;
        color: #9ca3af;
        margin-top: 4px;
        line-height: 1.4;
      }

      .form-actions {
        margin: 24px 0;

        .register-btn {
          width: 100%;
          height: 48px;
          background: #7c3aed;
          border: none;
          border-radius: 8px;
          font-weight: 600;
          font-size: 16px;

          &:hover:not(:disabled) {
            background: #6d28d9;
          }

          &:disabled {
            background: #cbd5e1;
            cursor: not-allowed;
          }
        }
      }

      .login-link {
        text-align: center;
        font-size: 14px;
        color: #64748b;

        .link {
          color: #7c3aed;
          text-decoration: none;
          margin-left: 4px;

          &:hover {
            color: #6d28d9;
            text-decoration: underline;
          }
        }
      }
    }
  }
}


// 动画关键帧
@keyframes fadeInChart {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 0.7;
    transform: translateX(0);
  }
}

@keyframes slideInStats {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .auth-container {
    flex-direction: column;
  }

  .brand-section {
    flex: none;
    padding: 20px;
    align-items: center;

    .brand-content {
      text-align: center;

      .brand-logo {
        position: static;
        margin-bottom: 20px;
      }

      .brand-text {
        .brand-title {
          font-size: 20px;
        }

        .brand-subtitle {
          font-size: 14px;
        }
      }
    }

    .financial-animation {
      position: static;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      gap: 12px;
      margin-top: 20px;
      pointer-events: auto;

      .main-chart {
        position: static;
        order: 1;
        width: 100%;
        display: flex;
        justify-content: center;
        margin-bottom: 16px;
      }

      .stats-display {
        position: static;
        order: 3;
        width: 100%;
        justify-content: center;

        .stat-item {
          padding: 12px;

          .stat-label {
            font-size: 11px;
          }

          .stat-value {
            font-size: 16px;
          }
        }
      }
    }
  }

  .form-section {
    flex: none;
    padding: 20px;

    .form-container {
      padding: 24px;
    }
  }
}

@media (max-width: 768px) {
  .auth-header {
    .header-container {
      padding: 0 16px;
    }
  }

  .brand-section {
    padding: 16px;
  }

  .form-section {
    padding: 16px;

    .form-container {
      padding: 20px;
      max-height: none;
    }
  }
}
</style>
